package com.hxx.controller;

import com.alibaba.fastjson2.JSON;
import com.hxx.domain.Person;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class TestDemo {

    /**
     * 对象转json
     */
    @Test
    public void test() {
        Person person = new Person(1, "张三", "男", 18);
        String jsonString = JSON.toJSONString(person);
        System.out.println(jsonString);
    }
    /**
     * json转对象
     */
    @Test
    public void test2() {
        String jsonString = "{\"id\":1,\"name\":\"张三\",\"sex\":\"男\",\"age\":18}";
        Person person = JSON.parseObject(jsonString, Person.class);
        System.out.println(person);
    }
    /**
     * 集合转json
     */
    @Test
    public void test3() {
        /*List<Person> personList = new ArrayList<>();
        personList.add(new Person(1, "张三", "男", 18));
        personList.add(new Person(2, "李四", "男", 19));
        personList.add(new Person(3, "王五", "男", 20));*/
        List<Person> personList = List.of(
                new Person(1, "张三", "男", 18),
                new Person(2, "李四", "男", 19),
                new Person(3, "王五", "男", 20)
        );
        String jsonString = JSON.toJSONString(personList);
        System.out.println(jsonString);
    }
    /**
     * json转集合
     */
    @Test
    public void test4() {
        String jsonString = "[{\"id\":1,\"name\":\"张三\",\"sex\":\"男\",\"age\":18},{\"id\":2,\"name\":\"李四\",\"sex\":\"男\",\"age\":19},{\"id\":3,\"name\":\"王五\",\"sex\":\"男\",\"age\":20}]";
        List<Person> personList = JSON.parseArray(jsonString, Person.class);
        System.out.println(personList);
    }
}






















